package pers.hxy.lookweather.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.util.Arrays;
import java.util.List;

import pers.hxy.lookweather.R;
import pers.hxy.lookweather.db.ChinaCitySqliteHelper;

/**
 * 从数据库保存的城市选择,只有国内的城市
 */
public class SelectCityActivity extends AppCompatActivity {
    private static final String TAG = "SelectCityActivity";
    private ChinaCitySqliteHelper sqliteHelper;
    private TextView tvCityInfo;
    private Button btnSelect;
    private Button btnBack;
    private Button btnCancel;
    private Spinner spinnerSelectLocation;
    private ArrayAdapter<String> adapter;
    private static final String EMPTY = "";
    private String locationID = EMPTY;
    private static final int N = 3;
    private final List<String>[] adm = new List[N];
    private final String[] names = new String[N];
    private int currentPosition = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_select_city);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        sqliteHelper = new ChinaCitySqliteHelper(getApplicationContext());
        tvCityInfo = findViewById(R.id.tv_city_info);
        btnSelect = findViewById(R.id.btn_select);
        btnBack = findViewById(R.id.btn_back);
        btnCancel = findViewById(R.id.btn_cancel);
        spinnerSelectLocation = findViewById(R.id.spinner_select_location);
        adapter = new ArrayAdapter<>(this, R.layout.item_select_city, R.id.tv_item_select_city);

        Arrays.fill(names, EMPTY);
        Arrays.fill(adm, null);

        btnSelect.setOnClickListener(v -> {
            Toast.makeText(this, "select id: " + locationID, Toast.LENGTH_SHORT).show();
            Intent intent = new Intent();
            intent.putExtra(WeatherActivity.INTENT_KEY_LOCATION_ID, locationID);
            intent.putExtra(WeatherActivity.INTENT_KEY_LOCATION_NAME, String.join("_", names));
            setResult(RESULT_OK, intent);
            sqliteHelper.close();
            finish();
        });

        btnBack.setOnClickListener(v -> {
            Log.d(TAG, "on click back");
            if (names[currentPosition].isEmpty()) {
                adm[currentPosition] = null;
                currentPosition--;
                updateAdapter();
            } else {
                spinnerSelectLocation.setSelection(0);
            }
        });

        btnCancel.setOnClickListener(v -> {
            setResult(RESULT_CANCELED);
            sqliteHelper.close();
            finish();
        });

        spinnerSelectLocation.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Log.d(TAG, "onItemSelected position=" + position + " currentPosition=" + currentPosition);
                if (position > 0) {
                    names[currentPosition] = adm[currentPosition].get(position);
                    currentPosition = Math.min(2, currentPosition + 1);
                } else {
                    names[currentPosition] = EMPTY;
                }
                update();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                Log.d(TAG, "onNothingSelected");
                locationID = EMPTY;
            }
        });

        update();
    }

    private void update() {
        Log.d(TAG, "update: currentPosition=" + currentPosition);
        if (adm[currentPosition] == null) {
            Log.d(TAG, "adm[" + currentPosition + "] is null");
            switch (currentPosition) {
                case 0: adm[0] = sqliteHelper.getAdm1_Name_ZH(); break;
                case 1: adm[1] = sqliteHelper.getAdm2_Name_ZH(names[0]); break;
                case 2: adm[2] = sqliteHelper.getLocation_Name_ZH(names[0], names[1]); break;
            }
            adm[currentPosition].add(0, "请选择");
            updateAdapter();
        }
        if (currentPosition == 2 && !names[2].isEmpty()) {
            locationID = sqliteHelper.getLocation_ID(names[0], names[1], names[2]);
            btnSelect.setEnabled(true);
        } else {
            locationID = EMPTY;
            btnSelect.setEnabled(false);
        }
        btnBack.setEnabled(currentPosition > 0);
        String info = String.join(" ", names) + "\n" + locationID;
        Log.d(TAG, "info: " + info);
        tvCityInfo.setText(info);
    }

    private void updateAdapter() {
        Log.d(TAG, "update adapter");
        adapter.clear();
        adapter.addAll(adm[currentPosition]);
        adapter.notifyDataSetChanged();
        spinnerSelectLocation.setAdapter(adapter);
        spinnerSelectLocation.setSelection(0);
    }
}
